package com.kylin.common.weixin.miniapp;

import com.alibaba.fastjson2.JSONObject;
import com.kylin.common.core.util.HttpUtils;
import com.kylin.common.weixin.util.WechatConstants;
import com.kylin.common.weixin.util.WxRequest;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * 小程序码相关接口
 * @author wuhao
 * @version 1.0 - 2023/11/20
 */
public class QrcodeService {

    public static Logger logger = LoggerFactory.getLogger(WxRequest.class);

    private static String WX_ACODE_UNLIMIT = "/wxa/getwxacodeunlimit";

    /**
     * 获取小程序二维码接口
     * @param scene 最大32个可见字符，只支持数字，大小写英文以及部分特殊字符：!#$&'()*+,/:;=?@-._~，其它字符请自行编码为合法字符（因不支持%，中文无法使用 urlencode 处理，请使用其他编码方式）
     * @param page 默认是主页，页面 page，例如 pages/index/index，根路径前不要填加 /，不能携带参数（参数请放在scene字段里），如果不填写这个字段，默认跳主页面。scancode_time为系统保留参数，不允许配置
     * @param envVersion 要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
     * @return
     * @author wuhao
     * @version 1.0.0 - 2023/4/15
     */
    public static byte[] getWxaCodeUnlimit(String scene , String page,String envVersion) {
        long begin = System.currentTimeMillis();
        JSONObject params = new JSONObject();
        params.put("scene", scene);
        params.put("page", page);
        params.put("env_version", envVersion);
        params.put("check_path", false);

        String url = WechatConstants.WX_API_URL  + WX_ACODE_UNLIMIT;
        CloseableHttpClient httpClient = HttpUtils.createHttpClient();
        HttpPost httpPost = new HttpPost(url);
        String result = "";
        try {
            StringEntity entity = new StringEntity(JSONObject.toJSONString(params), ContentType.IMAGE_PNG);
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try (InputStream inputStream = response.getEntity().getContent();
                 ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                result = new String(out.toByteArray());
                return out.toByteArray();
            }
        } catch (Exception e) {
            logger.error(url,e);
            e.printStackTrace();
        } finally {
            logger.info("\n【微信请求地址】: {}\n【微信请求参数】：{}\n【微信响应数据】：{}\n【微信接口耗时】:{}",
                    url, params, result,(System.currentTimeMillis() - begin)+"ms");
        }
        return null;
    }
}
